package com.kaaction.common.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.util.UriUtils;

import com.google.gson.Gson;
import com.kaaction.common.config.Global;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.StreamUploader;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * 查看CK上传的图片
 * @author ThinkGem
 * @version 2014-06-25
 */
public class QiniuServlet extends HttpServlet {
	private static final String ACCESS_KEY = "wklWur3MW4xPBqvPoSgvArkQ_1QDo_ZXUx-gyw76";
    private static final String SECRET_KEY = "ImuFNvds-ZaazvAtuz-Lbch1HwCbe7jvNynIM-DN";
    private static final String BUCKET_NAME = "kaacloud";

	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//构造一个带指定Zone对象的配置类
	static Configuration cfg = new Configuration(Zone.zone2());
	//...其他参数参考类注释
	static UploadManager uploadManager = new UploadManager(cfg);

	/**
     * 上传图片到七牛云存储
     * @param reader
     * @param fileName
     */
    public static void upload(HttpServletRequest req, HttpServletResponse resp) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        try {
			InputStream inputStream = req.getInputStream();
			int xx = (int)(Math.random() * 10000000);
			
			Response response = uploadManager.put(inputStream,""+xx+".jpg",upToken,null,"application/octet-stream");
	        //解析上传成功的结果
	        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
	        System.out.println(putRet.key);
	        System.out.println(putRet.hash);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println("token = " + upToken);
        System.out.println(upToken);
    }

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		upload(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		upload(req, resp);
	}
}
